using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;

namespace Stanford.Data
{
	public class EFRepository<T> : IRepository<T> where T : class
	{
		public IUnitOfWork UnitOfWork { get; set; }
		private IObjectSet<T> _objectset;
		private IObjectSet<T> ObjectSet
		{
			get
			{
				if (_objectset == null)
				{
					_objectset = UnitOfWork.Context.CreateObjectSet<T>();
				}
				return _objectset;
			}
		}

		public virtual IQueryable<T> All()
		{
			return ObjectSet.AsQueryable();
		}

		public virtual IQueryable<T> All(string includes)
		{
            ObjectQuery<T> Query = UnitOfWork.Context.CreateObjectSet<T>();
			if (!string.IsNullOrEmpty(includes))
            {
                foreach (string includeProperty in includes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Query = Query.Include(includeProperty.Trim());
                }
            }
            return Query;
		}

		public virtual IQueryable<T> All(List<string> lstInclude)
		{
            ObjectQuery<T> Query = UnitOfWork.Context.CreateObjectSet<T>();
			foreach(string itemInclude in lstInclude)
                Query = Query.Include(itemInclude.Trim());
            return Query;
		}

		public IQueryable<T> Find(Func<T, bool> expression)
		{
			return ObjectSet.Where(expression).AsQueryable();
		}

		public void Add(T entity)
		{
			ObjectSet.AddObject(entity);
		}

		public void Delete(T entity)
		{
			ObjectSet.DeleteObject(entity);
		}

		public void Save()
		{
			UnitOfWork.Save();
		}
	}
}